package com.bsh.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具
 * 
 * @author gsh
 *
 */
@Component
@Lazy(false)
public class UploadUtils {
	static String rootPath;
	
	public static String getRootPath() {
		return rootPath;
	}

	@Value("${upload.rootPath}")
	public void setRootPath(String _rootPath) {
		rootPath = _rootPath;
	}	
	
	private static boolean saveToLocal(MultipartFile file, String absPath) {
		if (!file.isEmpty()) {
			File localFile = new File(absPath);
			try {
				file.transferTo(localFile);
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			return true;
		}
		return false;
	}

	public static String save(MultipartFile file, String virtualDir) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sdf.format(new Date());
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String virtualDirPath = String.format(virtualDir+"/%s", dateStr);	
		
		String saveRootPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
		if(!StringUtils.isEmpty(UploadUtils.getRootPath()))
			saveRootPath=UploadUtils.getRootPath();
 		String absDirPath =saveRootPath + virtualDirPath;
 		absDirPath = absDirPath.replaceAll("\\/", "/");
		absDirPath = absDirPath.replaceAll("\\\\", "/");
		absDirPath = absDirPath.replaceAll("//", "/");
		File dir = new File(absDirPath);
		if (!dir.exists())
			dir.mkdirs();
		
		String newFileName=UUID.randomUUID() + suffix;
		String absPath = absDirPath + "/" + newFileName;
		
		String virtualPath=virtualDirPath + "/" + newFileName;
		saveToLocal(file, absPath);
		return virtualPath;
	}

	

}
